﻿using System;
using System.Linq;
using System.Linq.Expressions;
using LINQtoNHibernateMVC.Core.Domain;
using LINQtoNHibernateMVC.Core.Domain.Model;
using NHibernate;
using NHibernate.Linq;

namespace LINQtoNHibernateMVC.Infrastructure.DataAccess.Impl {
	public class Repository : IRepository {
		private readonly ISession _session;

		public Repository(ISession session)
		{
			_session = session;
		}

		public T Load<T>(object id) where T : Entity
		{
			return _session.Load<T>(id);
		}
		public T Get<T>(object id) where T : Entity
		{
			return _session.Get<T>(id);
		}
		public T Get<T>(Expression<Func<T, bool>> predicate) where T : Entity
		{
			 return _session.Linq<T>().SingleOrDefault(predicate);
		}

		public IQueryable<T> FindAll<T>() where T : Entity
		{
			return _session.Linq<T>();
		}
		
		public IQueryable<T> Find<T>(Expression<Func<T, bool>> predicate) where T : Entity
		{
			 return _session.Linq<T>().Where(predicate);
		}

		public void Add<T>(T entity) where T : Entity
		{
			 _session.Save(entity);
		}

		public void Remove<T>(T entity) where T : Entity
		{
			_session.Delete(entity);
		}

		public void SubmitChanges()
		{
			try
			{
				_session.Transaction.Commit();
				_session.BeginTransaction();
			}
			catch
			{
				_session.Transaction.Rollback();
				throw;
			}
		}
	}
}
